package cn.itcast.service.impl;

import cn.itcast.pojo.district;
import cn.itcast.pojo.districtExample;
import cn.itcast.pojo.user_address;
import cn.itcast.pojo.user_addressExample;
import cn.itcast.service.user_addressService;
import cn.itcast.util.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@SuppressWarnings("ALL")
@Service
public class user_addressServiceImpl implements user_addressService
{
    @Autowired
    cn.itcast.mapper.user_addressMapper user_addressMapper;

    @Resource
    cn.itcast.mapper.districtMapper districtMapper;

    @Autowired
    RedisUtil redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /*
     *功能：删除收货地址
     * @author 欧阳辉
     * @date 2019/5/29
      * @param addressId
     * @return boolean
     */
    @Override
    public boolean delectUser_address(user_address user_address) {
        boolean isdelect = false;
        //判断传入字段是否为空
        if (StringUtils.isNotBlank(ObjectUtils.toString(user_address.getAddressId()))){
            int i = user_addressMapper.deleteByPrimaryKey(user_address.getAddressId());
            if(i==1){
                isdelect = true;
                log.debug("删除数据成功");
            }else{
                log.debug("修改数据有误，不为1条，或者地址Id不存在");
            }
        }else {
            log.debug("地址Id为空");
        }

        return isdelect;
    }

    /*
     *功能：修改用户地址
     * @author 欧阳辉
     * @date 2019/5/29
      * @param user_address
     * @return boolean
     */
    @Override
    public boolean updateUser_address(user_address user_address) {
        boolean isupdate = false;
//        if(!StringUtils.isNotBlank(ObjectUtils.toString(redisTemplate.get(user_address.getTelephoneNumber()+"code")))){
//            return false;
//        }
//        int codeRedis = (int) redisTemplate.get(user_address.getTelephoneNumber()+"code");
//        log.debug(String.valueOf(codeRedis));
//        log.debug(String.valueOf(code));
//
//        if(Integer.parseInt(code)==codeRedis) {
            //判断传入字段是否为空
            if (StringUtils.isNotBlank(ObjectUtils.toString(user_address.getAddressId()))) {
                int i = user_addressMapper.updateByPrimaryKeySelective(user_address);
                if (i == 1) {
                    isupdate = true;
                    log.debug("修改数据成功");
                    redisTemplate.del("code");
                } else {
                    log.debug("修改数据有误，不为1条，或者地址Id不存在");
                }
            } else {
                log.debug("地址Id为空");
            }
//        }else{
//            return false;
//        }

        return isupdate;
    }

    /*
     *功能：添加收货地址
     * @author 欧阳辉
     * @date 2019/5/29
      * @param userAddress
     * @return boolean
     */
    @Override
   public boolean addUser_address(user_address userAddress){
        boolean isadd = false;
//
//        if(!StringUtils.isNotBlank(ObjectUtils.toString(redisTemplate.get(userAddress.getTelephoneNumber()+"code")))){
//            return false;
//        }
//        int codeRedis = (int) redisTemplate.get(userAddress.getTelephoneNumber()+"code");
//        log.debug(String.valueOf(codeRedis));
//        log.debug(String.valueOf(code));
//
//        if(code==codeRedis){
            //判断传入字段是否为空
            if (StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getUserName()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getDetailAddress()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getOpenId()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getCity()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getPostcode()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getCounty()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getIsdefault()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getTelephoneNumber()))
                    && StringUtils.isNotBlank(ObjectUtils.toString(userAddress.getProvince()))){

                //如果无地址，则设为默认地址
                user_addressExample uaEx = new user_addressExample();
                user_addressExample.Criteria criteria = uaEx.createCriteria();
                criteria.andOpenIdEqualTo(userAddress.getOpenId());
                List<user_address> user_addresses = user_addressMapper.selectByExample(uaEx);
                if(user_addresses.size()==0){
                    userAddress.setIsdefault(1);
                }
                int i = user_addressMapper.insertSelective(userAddress);

                if(i==1){
                    isadd = true;
                    log.debug("插入数据成功");
                    redisTemplate.del("code");
                }else{
                    log.debug("插入数据有误，不为1条");
                }
            }else {
                log.debug("数据缺少，某一个字段为空");
            }
//        }else{
//            return false;
//        }




        return isadd;
    }
    /*
     *功能：通过用户唯一标识
     * @author 欧阳辉
     * @date 2019/5/29
      * @param openId
     * @return java.util.List<cn.itcast.pojo.user_address>
     */
    @Override
    public List<user_address> findAllAddress(String openId) {
        user_addressExample uEx=new user_addressExample();
        user_addressExample.Criteria criteria = uEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        return user_addressMapper.selectByExample(uEx);
    }

    /**
     *功能：查询单个收货地址
     * @author 欧阳辉
     * @date 2019/6/6
      * @param addressId
     * @return cn.itcast.pojo.user_address
     */

    @Override
    public user_address findOneUser_address(Integer addressId) {
        return user_addressMapper.selectByPrimaryKey(addressId);
    }

    @Override
    public user_address getDefaultAddress(String openId) {
        user_addressExample uEx=new user_addressExample();
        user_addressExample.Criteria criteria = uEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andIsdefaultEqualTo(1);
        List<user_address> user_addresses = user_addressMapper.selectByExample(uEx);
        if(user_addresses.isEmpty()){
            return null;
        }else {
            return user_addresses.get(0);
        }
    }

    @Override
    public boolean updateDefaultAddress(int addressId,String openId) {
        user_addressExample uEx=new user_addressExample();
        user_addressExample.Criteria criteria = uEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andIsdefaultEqualTo(1);
        //修改旧的默认地址
        List<user_address> user_addresss = user_addressMapper.selectByExample(uEx);
        if(!user_addresss.isEmpty()){
            user_addresss.get(0).setIsdefault(0);
            user_addressMapper.updateByPrimaryKeySelective(user_addresss.get(0));
        }

        //增加新的默认地址
        user_address newuser_address = new user_address();
        newuser_address.setAddressId(addressId);
        newuser_address.setIsdefault(1);
        int i = user_addressMapper.updateByPrimaryKeySelective(newuser_address);
        if(i!=0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean isArea(String town) {
        if(town.equals("松山湖管委会")){
            town="大朗镇";
        }else if(town.equals("南城街道")){
            town="南城区";
        }else if(town.equals("东城街道")){
            town="东城区";
        }else if(town.equals("万江街道")){
            town="万江区";
        }else if(town.equals("莞城街道")){
            town="莞城区";
        }
        districtExample dEx = new districtExample();
        districtExample.Criteria criteria = dEx.createCriteria();
        criteria.andDistrictNameEqualTo(town);
        List<district> districts = districtMapper.selectByExample(dEx);
        for (district district : districts) {
            if(district.getIsOpen()==1){
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean getCode(String phone) {
        if(phone.equals("")){
            return false;
        }

        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(phone + "code", "6666");
        stringRedisTemplate.expire(phone + "code",180,TimeUnit.SECONDS);
        if (!ifAbsent){
            return false;
        }


        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4Ff8L6v5dqjTn8ymKLYs", "2JKuV67WyVhVbCRSmWpJTgbfO9aEkS");//广东速天
//        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIslHoiezqoXC6", "0QsOie6oOKdh207FG15734bQ2emPrL"); 杭州思软
        IAcsClient client = new DefaultAcsClient(profile);

        int num=(int)(Math.random()*8999)+1000;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "大黄牛智能回收");
        request.putQueryParameter("TemplateCode", "SMS_177480265");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+num+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
           log.debug(response.getData());
            JSONObject jsonObject = JSONObject.parseObject(response.getData());
           if(jsonObject.get("Code").equals("OK")){
               System.err.println(123);
               redisTemplate.set(phone+"code",num,180);

              return true;
           }else{
               return false;
           }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return true;
    }


}
